#include <iostream>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <thread>
using namespace std;


class FooBar {
private:
    int n;
    mutex mtx;
    condition_variable cv;
    bool foo_done=false;
public:
    FooBar(int n) {
        this->n = n;
    }
    void foo(function<void()> printFoo) {
        for (int i = 0; i < n; i++) {
            unique_lock<mutex>locker(mtx);
            cv.wait(locker,[&](){return foo_done==false;});
            printFoo();
            foo_done=true;
            cv.notify_one();
        }
    }
    void bar(function<void()> printBar) {
        for (int i = 0; i < n; i++) {
            unique_lock<mutex>locker(mtx);
            cv.wait(locker,[&](){return foo_done;});
            printBar();
            foo_done=false;
            cv.notify_one();
        }
    }
};

int main() {
    FooBar foo(3);  // 创建 Foo 类实例

    
    std::thread t1([&foo] {foo.foo([]{ std::cout << "foo"; });});
    std::thread t2([&foo] {foo.bar([]{ std::cout<<"bar\n";});});
    // 等待三个线程完成
    t1.join();
    t2.join();

    return 0;
}